package algorithm.dp;

public class 交错字符串 {
    /*
     * 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
     * 
     * 示例 1:
     * 
     * 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" 输出: true 示例 2:
     * 
     * 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" 输出: false
     * 
     * 来源：力扣（LeetCode） 链接：https://leetcode-cn.com/problems/interleaving-string
     * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
     * 
     */
    public boolean isInterleave(String s1, String s2, String s3) {
        /*
         * s3[n-1] = s1[0:i-1]+s2[0:j-1]，如果s3[n] =
         * s1[i],那么s3[n]=s1[0:i]+s2[0:j-1]或者s3[n]=s2[j]，那么s3[n]=s1[0:i-1]+s2[0:j] 
         * 执行用时 : 13 ms , 在所有Java提交中击败了 24.70% 的用户 内存消耗 : 34.4 MB ,
         * 在所有Java提交中击败了 46.29% 的用户
         */
        int len1 = s1.length();
        int len2 = s2.length();
        int len3 = s3.length();
        if (len3 != len1 + len2) {
            return false;
        }
        boolean[][] dp = new boolean[len1 + 5][len2 + 5];
        dp[0][0] = true;
        for (int i = 0; i <= len1; i++) {
            for (int j = 0; j <= len2; j++) {
                if (i != 0 && s1.charAt(i - 1) == s3.charAt(i + j - 1)) {
                    dp[i][j] = dp[i - 1][j];
                }
                if (j != 0 && !dp[i][j] && s2.charAt(j - 1) == s3.charAt(i + j - 1)) {
                    dp[i][j] = dp[i][j - 1];
                }
            }
        }
        return dp[len1][len2];
    }

    public static void main(String[] args) {
        交错字符串 run = new 交错字符串();
        System.out.println(run.isInterleave("ab", "bc", "babc"));
    }
}
